package com.xored.glance.ui.controls.tree;

import java.util.HashMap;
import java.util.Map;

import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.swt.events.TreeEvent;
import org.eclipse.swt.events.TreeListener;
import org.eclipse.swt.widgets.Tree;
import org.eclipse.swt.widgets.TreeItem;

import com.xored.glance.ui.controls.tree.content.TreeContent;
import com.xored.glance.ui.controls.tree.content.TreeItemContent;
import com.xored.glance.ui.controls.tree.content.TreeNode;

public class TreeControlContent extends TreeContent implements TreeListener {

	private Tree tree;
	private Map<TreeCell, TreeItemContent> cellToContent = new HashMap<TreeCell, TreeItemContent>();

	public TreeControlContent(Tree tree) {
		this.tree = tree;
		tree.addTreeListener(this);
		collectCells(this, tree.getItems());
	}

	@Override
	public void dispose() {
		if (!tree.isDisposed()) {
			tree.removeTreeListener(this);
		}
	}

	@Override
	public TreeItemContent getContent(TreeCell cell) {
		return cellToContent.get(cell);
	}

	@Override
	public void index(IProgressMonitor monitor) {
		// No index here
	}

	private void collectCells(TreeNode node, TreeItem[] items) {
		if (items.length > 0) {
			int columns = items[0].getParent().getColumnCount();
			if (columns == 0) {
				columns = 1;
			}
			TreeNode[] nodes = new TreeNode[items.length];
			for (int i = 0; i < nodes.length; i++) {
				TreeItem item = items[i];
				nodes[i] = new TreeNode();
				for (int j = 0; j < columns; j++) {
					TreeCell cell = new TreeCell(item, j);
					TreeItemContent itemContent = new TreeItemContent(nodes[i],
							item.getText(), j);
					cellToContent.put(cell, itemContent);
				}
				if (item.getExpanded()) {
					collectCells(nodes[i], item.getItems());
				}
			}
			node.add(nodes);
		}
	}

	public void treeExpanded(TreeEvent event) {
		if (event.item instanceof TreeItem) {
			TreeItem item = (TreeItem) event.item;
			TreeItemContent content = getContent(item);
			collectCells(content.getNode(), item.getItems());
		}
	}

	public void treeCollapsed(TreeEvent event) {
		if (event.item instanceof TreeItem) {
			TreeItemContent content = getContent((TreeItem) event.item);
			TreeNode node = content.getNode();
			node.remove(node.getChildren());
		}
	}

	private TreeItemContent getContent(TreeItem item) {
		return cellToContent.get(new TreeCell(item, 0));
	}

}
